package com.yf.exam.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.yf.exam.modules.trainingarchives.pdfexport.from.PdfFormTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.*;

/**
 * pdfItext5工具类
 *
 */
@Slf4j
public class PdfItext5Util {

    /**
     * 每页显示数，可自行修改
     */
    public static final int PAGE_SIZE = 12;

    /**
     * 临时文件路径
     */
    public final static String FOLDER = "/Users/gengjiaxuan/Downloads/tempPdfFile";

    /**
     * 文件路径
     */
    public final static String FOLDER_PATH = FOLDER + "/";

    /**
     * 获取pdf字节数组列表
     *
     * @param template
     * @return
     */
    public static String createPdf(PdfFormTemplate template) throws Exception {
        List<PdfReader> pdfReaderList = new ArrayList<>(Collections.emptyList());

        // 数据分页
        List<List<Map<String, String>>> pageList = Lists.partition(template.getPageDataList(), PAGE_SIZE);
        int pageTotal = pageList.size();
        for (int i = 0; i < pageList.size(); i++) {
            // 生成每页pdf的字节数组
            PdfReader currentPagePdf = createCurrentPagePdf(template, pageList.get(i), (i + 1), pageTotal);
            pdfReaderList.add(currentPagePdf);
        }

        // 合并后生成文件的目标路径
        String destPdfPath = StringUtils.join(
                template.isGenerateToLocalFileFlag() ? template.getLocalFileStoragePath() : FOLDER_PATH,
                System.currentTimeMillis(),
                template.getTemplateFileName(),
                ".pdf"
        );

        //输出流
        FileOutputStream outputStream = new FileOutputStream(destPdfPath);
        Document document = new Document(new PdfReader(pdfReaderList.get(0)).getPageSize(1));
        PdfSmartCopy copy = new PdfSmartCopy(document, outputStream);
        document.open();
        //合并所有分页pdf
        for (int k = 1; k <= pdfReaderList.size(); k++) {
            PdfReader reader = pdfReaderList.get(k - 1);
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, 1);
            copy.addPage(page);
        }
        copy.close();
        outputStream.close();

        return destPdfPath;
    }

    /**
     * 获取分页pdf
     *
     * @param template pdf表单模版
     * @param currentTableData 当前页表格数据
     * @param currentPage 当前页
     * @param pageCount 总页数
     * @return
     * @throws Exception
     */
    /**
     * 生成当前页pdf字节数组
     *
     * @param template
     * @param currentPageDataList
     * @param currentPageNo
     * @param pageTotal
     * @return
     */
    private static PdfReader createCurrentPagePdf(PdfFormTemplate template, List<Map<String, String>> currentPageDataList, int currentPageNo, int pageTotal) throws Exception {
        PdfReader templateReader;
        ByteArrayOutputStream bos;
        //读取pdf模板
        templateReader = new PdfReader(template.getTemplatePath());
        bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(templateReader, bos);
        AcroFields form = stamper.getAcroFields();

        // 自定义字体设置
        /*BaseFont baseFont;
        if (isWindowsSystem()) {
            baseFont = BaseFont.createFont("/fonts/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } else {
            baseFont = BaseFont.createFont("/fonts/extend/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        form.setSubstitutionFonts(Lists.newArrayList(baseFont));*/

        // 设置页码
        form.setField(template.getCustomPageNoFiledName(), StringUtils.join(currentPageNo, "/", pageTotal));
        // 填充基本信息
        Map<String, String> baseDataMap = template.getBaseDataMap();
        if (CollUtil.isNotEmpty(baseDataMap)) {
            for (String dataKey : baseDataMap.keySet()) {
                form.setField(dataKey, baseDataMap.get(dataKey));
            }
        }

        if (CollUtil.isNotEmpty(currentPageDataList)) {
            int i = 1;
            // 填充分页数据
            for (Map<String, String> currentPageDataMap : currentPageDataList) {
                // 填充序号, 可以自定义属性，从外部传入
                form.setField("no", String.valueOf((currentPageNo - 1) * PAGE_SIZE + i));
                // 填充其他数据
                Set<Map.Entry<String, String>> entries = currentPageDataMap.entrySet();
                int finalNo = i;
                entries.forEach(entry -> {
                    try {
                        form.setField(StringUtils.join(entry.getKey(), finalNo), entry.getValue());
                    } catch (Exception e) {
                        log.error("填充表单数据异常", e);
                    }
                });
                i++;
            }
        }

        /*Map<String, AcroFields.Item> formFields = form.getFields();
        for (String key : formFields.keySet()) {
            form.setFieldProperty(key, "textfont", baseFont, null);
            form.setFieldProperty(key, "textsize", 8f, null);
        }*/

        String pagePdfPath = FOLDER_PATH + System.currentTimeMillis() + ".pdf";
        FileOutputStream outputStream = new FileOutputStream(pagePdfPath);
        //如果为false那么生成的PDF文件还能编辑，一定要设为true
        stamper.setFormFlattening(true);
        stamper.close();
        Document doc = new Document();
        PdfSmartCopy copy = new PdfSmartCopy(doc, outputStream);
        doc.open();
        PdfReader reader = new PdfReader(bos.toByteArray());
        PdfImportedPage importPage = copy.getImportedPage(reader, 1);
        copy.addPage(importPage);
        doc.close();
        outputStream.close();
        return reader;
    }

    /**
     * 判断当前系统是否是Windows系统
     *
     * @return
     */
    public static boolean isWindowsSystem() {
        String property = System.getProperty("os.name").toLowerCase();
        return property.contains("windows");
    }
}
